package basicelement;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.ExampleSet;

import com.rapidminer.example.Example;
import com.rapidminer.example.table.AttributeFactory;


import istar.IElement;
import istar.ITask;
import istar.agent.IstarJadeAgent;
import istar.behaviour.IstarBehaviour;
import istar.impl.AbstractBasicTask;
import istar.impl.Belief;
import istar.impl.MeansEndLink;
import istar.impl.Task;
import istar.impl.TaskDecompositionLink;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;


public class Ponder extends AbstractBasicTask{

	private boolean log = true;
	
	public Ponder() {
		super("Ponder"); 
	}

	@Override
	public Behaviour getBehaviour() {
		return new myBehaviour(this);
	}
	
	private class myBehaviour extends IstarBehaviour{

		AbstractBasicTask task;
		
		/*
		public myBehaviour(Agent a, AbstractBasicTask _task){
			super(a);
			task = _task;
			this.setBehaviourName("Ponder");
		}
		*/

		public myBehaviour(AbstractBasicTask _task){
			super(_task);
		}

		
		@Override
		public void myAction() {
			/*
			Example example = (Example)((IstarJadeAgent)myAgent).getKnowledgeElement(task.getExecutionNumber(), "Example");
			Double predMin = (Double)((IstarJadeAgent)myAgent).getKnowledgeElement(task.getExecutionNumber(), "NextMin");
			Double predMax = (Double)((IstarJadeAgent)myAgent).getKnowledgeElement(task.getExecutionNumber(), "NextMax");
			
			System.out.println("NextMin: "+ predMin.toString());
			System.out.println("NextMax: "+ predMax.toString());
		
			Double lastMax = example.getValue(example.getAttributes().get("Maxima-atual"));
			Double lastMin = example.getValue(example.getAttributes().get("Minima-atual"));
			Double lastPrice = example.getValue(example.getAttributes().get("LAST_PRICE"));
			String id =  example.getValueAsString(example.getAttributes().getId());
			TendencyIndicator tendency = new TendencyIndicator(id, lastPrice, lastMin, lastMax, predMin, predMax);
			*/
			
			try {
				
				TendencyIndicator tendency = null;
				IElement previousTask = (IElement)((IstarJadeAgent)myAgent).getKnowledgeElement(task.getExecutionNumber(), task.getPreviousElement().getId());
				for (int i=0;i<previousTask.getContent().size();i++){
					if (previousTask.getContent().get(i).getClass().equals(TendencyIndicator.class))
						tendency = (TendencyIndicator)previousTask.getContent().get(i);
				}
				if (tendency==null)
					throw new Exception("Tendency not found");

				
				((IstarJadeAgent)myAgent).getShortTermMemory().put(tendency.getInstantTime().toString(), tendency);

				System.out.println("Tendency:" + tendency.toString());
				Belief futurePrice = null;
				
				Iterator<TaskDecompositionLink> itDecompositionLinks = task.getSupports().iterator();
				while (itDecompositionLinks.hasNext()){
					IElement father = itDecompositionLinks.next().getOwner();
					if (father.getName().equals("GenerateBelief")){
						Iterator<MeansEndLink> itMeansEnds = ((Task)father).getMeansFor().iterator();
						while (itMeansEnds.hasNext()){
							IElement grandFather = itMeansEnds.next().getOwner();
							if (grandFather.getName().equals("FuturePrice"))
								futurePrice = (Belief)grandFather;
						}
					}
				}
				
				//System.out.println("Future Price content: " + futurePrice.getContent().toString());

				((IstarJadeAgent)myAgent).getBeliefs().remove(futurePrice);
				IElement actionBeChosen = (IElement)futurePrice.getEvaluationLink().getTargetGoal();
				Iterator<IElement> itMeans = actionBeChosen.getMeansEndLink().getTargetElements().iterator();
				while (itMeans.hasNext()){
					ITask mean = (ITask)itMeans.next();
					Double eval = evaluateMeanTask(tendency, mean);
					System.out.println("============");
					System.out.println("Mean:" + mean.getName() + " - eval:" + eval);
					futurePrice.getAssessments().put(mean, eval);
				}
				
				((IstarJadeAgent)myAgent).getBeliefs().add(futurePrice);
				
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		private Double evaluateMeanTask(TendencyIndicator tendency, ITask mean){
			try {
				Date instant = tendency.getInstantTime(); 
				Calendar cal = Calendar.getInstance();
				cal.setTime(instant);
				int previousMinute = cal.get(Calendar.MINUTE);
				int hour =  cal.get(Calendar.HOUR);
				int day = cal.get(Calendar.DAY_OF_MONTH);
				int month = cal.get(Calendar.MONTH) + 1;
				int year = cal.get(Calendar.YEAR);
				
				previousMinute --;
				
				String prev = day+"/"+month+"/"+year+" "+hour+":"+previousMinute;
				Date previousInstant = TendencyIndicator.formatDate(prev);
				
				TendencyIndicator previousTendency = (TendencyIndicator)((IstarJadeAgent)myAgent).getShortTermMemory().get(previousInstant.toString());
				if (previousTendency!=null){
					if (previousTendency.getTendency()==tendency.getTendency()){
						if (tendency.getTendency()>0){
							if (mean.getName().toUpperCase().equals("BUY"))
								return new Double(tendency.getTendency());
							else
								return new Double(-tendency.getTendency());
						}
						if (tendency.getTendency()<0){
							if (mean.getName().toUpperCase().equals("SELL"))
								return new Double(-tendency.getTendency());
							else
								return new Double(tendency.getTendency());
						}
					}
				}
				
				if (mean.getName().equals("DoNothing"))
					return new Double(1);
				else
					return new Double(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return new Double(Belief.NEUTRAL);
		}
		
		@Override
		public int myOnEnd() {
			// TODO Auto-generated method stub
			return 1;
		}

		@Override
		public boolean done() {
			return true;
		}

	}
	
}
